{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "53d35101-c905-4f78-bb58-9fcbec5c99ca",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-11-18T12:24:19.627300Z",
     "iopub.status.busy": "2025-11-18T12:24:19.627078Z",
     "iopub.status.idle": "2025-11-18T12:24:19.631874Z",
     "shell.execute_reply": "2025-11-18T12:24:19.631498Z",
     "shell.execute_reply.started": "2025-11-18T12:24:19.627284Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "llm 调用 tools,让llm 和外界交流\n"
     ]
    }
   ],
   "source": [
    "print(\"llm 调用 tools,让llm 和外界交流\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "e6557aab-ecb6-4788-86fd-67925451c1e4",
   "metadata": {
    "ExecutionIndicator": {
     "show": true
    },
    "execution": {
     "iopub.execute_input": "2025-11-18T12:27:21.260423Z",
     "iopub.status.busy": "2025-11-18T12:27:21.260225Z",
     "iopub.status.idle": "2025-11-18T12:27:29.565417Z",
     "shell.execute_reply": "2025-11-18T12:27:29.564871Z",
     "shell.execute_reply.started": "2025-11-18T12:27:21.260408Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Looking in indexes: https://mirrors.cloud.aliyuncs.com/pypi/simple\n",
      "Requirement already satisfied: requests in /usr/local/lib/python3.11/site-packages (2.32.3)\n",
      "Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.11/site-packages (from requests) (3.4.1)\n",
      "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.11/site-packages (from requests) (3.10)\n",
      "Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.11/site-packages (from requests) (2.3.0)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.11/site-packages (from requests) (2025.1.31)\n",
      "\u001b[33mDEPRECATION: pytorch-lightning 1.7.7 has a non-standard dependency specifier torch>=1.9.*. pip 24.0 will enforce this behaviour change. A possible replacement is to upgrade to a newer version of pytorch-lightning or contact the author to suggest that they release a version with a conforming dependency specifiers. Discussion can be found at https://github.com/pypa/pip/issues/12063\u001b[0m\u001b[33m\n",
      "\u001b[0m\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
      "\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.3.2\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m25.3\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n",
      "Looking in indexes: https://mirrors.cloud.aliyuncs.com/pypi/simple\n",
      "Requirement already satisfied: openai in /usr/local/lib/python3.11/site-packages (2.3.0)\n",
      "Requirement already satisfied: anyio<5,>=3.5.0 in /usr/local/lib/python3.11/site-packages (from openai) (4.11.0)\n",
      "Requirement already satisfied: distro<2,>=1.7.0 in /usr/local/lib/python3.11/site-packages (from openai) (1.9.0)\n",
      "Requirement already satisfied: httpx<1,>=0.23.0 in /usr/local/lib/python3.11/site-packages (from openai) (0.28.1)\n",
      "Requirement already satisfied: jiter<1,>=0.10.0 in /usr/local/lib/python3.11/site-packages (from openai) (0.11.0)\n",
      "Requirement already satisfied: pydantic<3,>=1.9.0 in /usr/local/lib/python3.11/site-packages (from openai) (2.11.10)\n",
      "Requirement already satisfied: sniffio in /usr/local/lib/python3.11/site-packages (from openai) (1.3.1)\n",
      "Requirement already satisfied: tqdm>4 in /usr/local/lib/python3.11/site-packages (from openai) (4.67.1)\n",
      "Requirement already satisfied: typing-extensions<5,>=4.11 in /usr/local/lib/python3.11/site-packages (from openai) (4.15.0)\n",
      "Requirement already satisfied: idna>=2.8 in /usr/local/lib/python3.11/site-packages (from anyio<5,>=3.5.0->openai) (3.10)\n",
      "Requirement already satisfied: certifi in /usr/local/lib/python3.11/site-packages (from httpx<1,>=0.23.0->openai) (2025.1.31)\n",
      "Requirement already satisfied: httpcore==1.* in /usr/local/lib/python3.11/site-packages (from httpx<1,>=0.23.0->openai) (1.0.9)\n",
      "Requirement already satisfied: h11>=0.16 in /usr/local/lib/python3.11/site-packages (from httpcore==1.*->httpx<1,>=0.23.0->openai) (0.16.0)\n",
      "Requirement already satisfied: annotated-types>=0.6.0 in /usr/local/lib/python3.11/site-packages (from pydantic<3,>=1.9.0->openai) (0.7.0)\n",
      "Requirement already satisfied: pydantic-core==2.33.2 in /usr/local/lib/python3.11/site-packages (from pydantic<3,>=1.9.0->openai) (2.33.2)\n",
      "Requirement already satisfied: typing-inspection>=0.4.0 in /usr/local/lib/python3.11/site-packages (from pydantic<3,>=1.9.0->openai) (0.4.2)\n",
      "\u001b[33mDEPRECATION: pytorch-lightning 1.7.7 has a non-standard dependency specifier torch>=1.9.*. pip 24.0 will enforce this behaviour change. A possible replacement is to upgrade to a newer version of pytorch-lightning or contact the author to suggest that they release a version with a conforming dependency specifiers. Discussion can be found at https://github.com/pypa/pip/issues/12063\u001b[0m\u001b[33m\n",
      "\u001b[0m\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n",
      "\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.3.2\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m25.3\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "# npm install \n",
    "# 发起请求\n",
    "!pip install requests\n",
    "\n",
    "!pip install openai"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "027f1230-261c-4461-8930-6c40e19202e7",
   "metadata": {
    "ExecutionIndicator": {
     "show": true
    },
    "execution": {
     "iopub.execute_input": "2025-11-18T12:49:13.207122Z",
     "iopub.status.busy": "2025-11-18T12:49:13.206915Z",
     "iopub.status.idle": "2025-11-18T12:49:13.263800Z",
     "shell.execute_reply": "2025-11-18T12:49:13.263370Z",
     "shell.execute_reply.started": "2025-11-18T12:49:13.207108Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'results': [{'location': {'id': 'WSFXR95RZD21', 'name': '抚州', 'country': 'CN', 'path': '抚州,抚州,江西,中国', 'timezone': 'Asia/Shanghai', 'timezone_offset': '+08:00'}, 'now': {'text': '阴', 'code': '9', 'temperature': '8'}, 'last_update': '2025-11-18T20:37:05+08:00'}]}\n",
      "抚州当前天气：阴, 气温 8度\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "# python 类型约定，\n",
    "# js 弱类型语言 \n",
    "# -> str 返回值的类型\n",
    "def get_weather(location: str) -> str:\n",
    "    url = \"https://api.seniverse.com/v3/weather/now.json\"\n",
    "    params = {\n",
    "        \"key\": \"SaVSOt7sYbwpka9iv\",\n",
    "        \"location\": location,\n",
    "        \"language\": \"zh-Hans\"\n",
    "    }\n",
    "    try:\n",
    "        resp = requests.get(url, params=params, timeout=10)\n",
    "        data = resp.json()\n",
    "        print(data)\n",
    "        if \"results\" in data:\n",
    "            r = data[\"results\"][0]\n",
    "            city = r[\"location\"][\"name\"]\n",
    "            # 当前天气对象\n",
    "            now = r[\"now\"]\n",
    "            text = now[\"text\"]\n",
    "            temp = now[\"temperature\"]\n",
    "            #python 擅长机器学习 和字符处理\n",
    "            return f\"{city}当前天气：{text}, 气温 {temp}度\"\n",
    "        else:\n",
    "            return \"查询失败\"\n",
    "    except Exception as e:\n",
    "        return  f\"异常：{e}\"\n",
    "    \n",
    "print(get_weather(\"抚州\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "c9310024-314b-4c85-a61c-4abcf3d73ff4",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-11-18T12:55:35.174133Z",
     "iopub.status.busy": "2025-11-18T12:55:35.173890Z",
     "iopub.status.idle": "2025-11-18T12:55:35.620301Z",
     "shell.execute_reply": "2025-11-18T12:55:35.619839Z",
     "shell.execute_reply.started": "2025-11-18T12:55:35.174117Z"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# 用户user向llm 提问 自然语言\n",
    "# 实时性的， 工具类的， llm 无法回答\n",
    "# llm和原有的互联网文明桥接起来？ 智能互联网来了\n",
    "# tools 来自openai 接口定义， \n",
    "from openai import OpenAI\n",
    "\n",
    "client = OpenAI(\n",
    "    api_key = 'sk-b96af4b3f3f7406ca872a01ee7276f95',\n",
    "    base_url = 'https://api.deepseek.com/v1'\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "f6b7983c-a2d1-4895-bb9f-85afa7026b18",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-11-18T13:07:55.425013Z",
     "iopub.status.busy": "2025-11-18T13:07:55.424754Z",
     "iopub.status.idle": "2025-11-18T13:07:55.428424Z",
     "shell.execute_reply": "2025-11-18T13:07:55.427904Z",
     "shell.execute_reply.started": "2025-11-18T13:07:55.424995Z"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "# openai 接口定义\n",
    "tools = [\n",
    "    # JSON 定义\n",
    "    {\n",
    "        # 一个工具就是一个函数\n",
    "        \"type\": \"function\",\n",
    "        # 函数的申明\n",
    "        \"function\": {\n",
    "            \"name\": \"get_weather\",\n",
    "            \"description\": \"获取指定城市的当前天气\",\n",
    "            \"parameters\": {\n",
    "                \"type\": \"object\",\n",
    "                \"properties\": {\n",
    "                    \"location\": {\n",
    "                        \"type\": \"string\",\n",
    "                        # 北京天气怎么样？提取出来北京\n",
    "                        \"description\": \"城市名称，如'北京'\"\n",
    "                    }\n",
    "                },\n",
    "                \"required\": [\"location\"]\n",
    "            }\n",
    "        }\n",
    "    }\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "12a4e1c0-724c-4bce-a995-1dd1304b57b0",
   "metadata": {
    "ExecutionIndicator": {
     "show": true
    },
    "execution": {
     "iopub.execute_input": "2025-11-18T13:34:29.715126Z",
     "iopub.status.busy": "2025-11-18T13:34:29.714891Z",
     "iopub.status.idle": "2025-11-18T13:34:35.864310Z",
     "shell.execute_reply": "2025-11-18T13:34:35.863900Z",
     "shell.execute_reply.started": "2025-11-18T13:34:29.715110Z"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ChatCompletionMessage(content='我来帮您查询北京的天气情况。', refusal=None, role='assistant', annotations=None, audio=None, function_call=None, tool_calls=[ChatCompletionMessageFunctionToolCall(id='call_00_8GOm91zqN5qQjlEw9ghkxbzd', function=Function(arguments='{\"location\": \"北京\"}', name='get_weather'), type='function', index=0)])\n",
      "{'results': [{'location': {'id': 'WX4FBXXFKE4F', 'name': '北京', 'country': 'CN', 'path': '北京,北京,中国', 'timezone': 'Asia/Shanghai', 'timezone_offset': '+08:00'}, 'now': {'text': '晴', 'code': '1', 'temperature': '3'}, 'last_update': '2025-11-18T21:27:31+08:00'}]}\n",
      "根据查询结果，北京当前天气情况：\n",
      "\n",
      "- **天气状况**：晴 ☀️\n",
      "- **当前气温**：3°C\n",
      "\n",
      "今天北京天气不错，阳光明媚，但气温较低，建议您：\n",
      "- 外出时注意保暖，穿着厚外套\n",
      "- 由于天气晴朗，适合户外活动\n",
      "- 早晚温差可能较大，注意适时增减衣物\n",
      "\n",
      "需要了解未来几天的天气预报吗？我可以为您查询更详细的天气信息。\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "messages = [{\"role\": \"user\", \"content\": \"北京天气怎么样\"}]\n",
    "response = client.chat.completions.create(\n",
    "    model = 'deepseek-reasoner',\n",
    "    messages = messages,\n",
    "    tools = tools,\n",
    "    tool_choice = \"auto\",\n",
    "    # 生成的随机度\n",
    "    temperature = 0.3\n",
    ")\n",
    "response_message = response.choices[0].message\n",
    "# 多轮会话\n",
    "print(response_message)\n",
    "# tool_calls ChatCompletionMessageFunctionToolCall\n",
    "messages.append(response_message)\n",
    "if response_message.tool_calls:\n",
    "    for tool_call in response_message.tool_calls:\n",
    "        function_name = tool_call.function.name\n",
    "        # json 字符串变成json 对象\n",
    "        function_args = json.loads(tool_call.function.arguments)\n",
    "        if function_name == \"get_weather\":\n",
    "            function_response = get_weather(function_args[\"location\"])\n",
    "        else:\n",
    "            function_response = \"未知工具\"\n",
    "        messages.append({\n",
    "            \"tool_call_id\": tool_call.id,\n",
    "            \"role\": \"tool\",\n",
    "            \"name\": function_name,\n",
    "            \"content\": function_response\n",
    "        })\n",
    "else:\n",
    "    print(response_message.content)\n",
    "\n",
    "final_response = client.chat.completions.create(\n",
    "    model=\"deepseek-reasoner\",\n",
    "    messages=messages,\n",
    "    temperature=0.3\n",
    ")\n",
    "print(final_response.choices[0].message.content)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
